package org.ualr.cpsc.server;

import java.io.IOException;
import java.util.List;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesServiceFactory;

public class PhotoService {
    private static final long serialVersionUID = -4710761381319748535L;
    private static DataStore db = new DataStore();
    
    public static List<Photo> getUserPhotos() {
        return db.queryPhotos();
    }
    
    public static String addPhoto(String name, byte[] data, boolean isPublic) {
        Photo photo = new Photo();
        Image image = ImagesServiceFactory.makeImage(data);
        photo.setPublic(isPublic);
        photo.setWidth(image.getWidth());
        photo.setHeight(image.getHeight());
        try {
            String uuid = photo.getUUID();
            photo.setUrl(DataStore.storeFile(uuid, getMimeType(name), data));
            return db.updatePhoto(photo).getUrl();
        } catch (IOException ioe) {
            return null;
        }
    }
    
    private static String getMimeType(String name) {
        String extension = getExtension(name);
        if (extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("jpeg")) {
            return "image/jpeg";
        } else if (extension.equalsIgnoreCase("png")) {
            return "image/png";
        } else if (extension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        } else if (extension.equalsIgnoreCase("gif")) {
            return "image/gif";
        } else {
            return "application/octet-stream";
        }
    }
    
    public static String getExtension(String filename) {
        if (filename == null) return null;
        int index = filename.lastIndexOf('.');
        if (index == -1) return "";
        return filename.substring(index+1).toLowerCase();
    }
}
